var express = require('express');

var router = express.Router();
const PassageModel = require('../model/passage')
const CategoryModel = require('../model/category')
const VisitedAndStarModel = require('../model/visited')
const ManagerModel = require('../model/mannager')
const UserModel = require('../model/user')

// 用户认证模块
const jwt = require('jsonwebtoken')
const signkey = 'mes_qdhd_mobile_xhykjyxgs'; // 签名

const mongoose = require('mongoose');
const filter = { context: 0 ,comments: 0}//过滤的文章内容属性
const filter2 = { context: 0, info: 0, comments: 0 }


const ArticleModel = require('../model/acticle')
const ArticleCateModel = require('../model/articlecate');
// const { request } = require('express');


//----------------------------------------------测试内容区域--------------------
router.post('/test', function (req, res, next) {
  const { title } = req.body
  const category = new ArticleCateModel({ title })
  category.save(function (err, category) {
    if (category) {
      res.send({ code: 0 })
    } else {
      res.send({ code: 1, msg: '创建分类失败' })
    }
  })
})
router.post('/test2', function (req, res, next) {
  const { title, cid } = req.body
  const category = new ArticleModel({ title, cid })
  category.save(function (err, category) {
    if (category) {
      res.send({ code: 0 })
    } else {
      res.send({ code: 1, msg: '创建分类失败' })
    }
  })
})
router.post('/test3', function (req, res, next) {
  
  ArticleModel.aggregate([
    {
      $lookup: {
        from: 'articlecate',
        localField: "cid",
        foreignField: "_id",
        as: "cate",
      }
    }

  ], function (err, docs) {
    console.log(err)
    res.send({ code: 0, data: docs })
  })
});

// 添加
router.post('/addvisited', function (req, res, next) {
  /* 
const VisitedSchema =  new mongoose.Schema({
    //分类id会默认创建，使用默认的id
    visited_count:{type:Number,require:true}, // 访问数量
    star_count:{type:Number,require:true}, // star数量
    time:{type:Number,require:true},// 时间
})
*/
  let { visited_count, star_count, time } = req.body
  const visited = new VisitedAndStarModel({ visited_count, star_count, time })
  visited.save(function (err, vs) {
    if (vs) {
      res.send({ code: 0 })
    } else {
      res.send({ code: 1, msg: '创建分类失败' })
    }
  })
});
//----------------------------------------------测试内容结束--------------------
/* GET home page. */

// *****************前台的接口*****************
//主页获取文章的简介
router.get('/passage_info', function (req, res, next) {

  // const {passageID} = req.query
  PassageModel.find({isAuthor: true}, filter, function (error, passages) {
    //console.log(passages)
    console.log("获取文章摘要")
    res.send({ code: 0, data: passages })
  })
});
/* 
// 整体访客数量加一
      let time = (new Date())
      let hour = time.getHours()
      let min = time.getMinutes()
      let sec = time.getSeconds()
      let now_time = time - hour*3600*1000 - min*60*1000 - sec*1000
      // 让对应的项自增一
      VisitedAndStarModel.updateOne({time:now_time},{$inc:{visited_count:1}},{upsert:true},function(err,vs){
        if(!err){
          res.send({code:0,data:vs})
        } else{
          res.send({code:1,msg:'出错了'})
        }
      })
*/
//查看文章 ，同时用户的文章访问量加一 当天访问量加一
router.get('/passage', function (req, res, next) {

  const { passageID } = req.query
  PassageModel.findOneAndUpdate({ _id: passageID }, { $inc: { visited: 1 } }, function (error, passages) {
    if (!error) {
      // 整体访客数量加一
      let time = new Date()
      let hour = time.getHours()
      let min = time.getMinutes()
      let sec = time.getSeconds()
      // 十三位的时间戳是精确到毫秒的，这个容易遗漏
      let hm = time.getMilliseconds()
      let now_time = time - hour * 3600 * 1000 - min * 60 * 1000 - sec * 1000 - hm
      // 让对应的项自增一
      VisitedAndStarModel.updateOne({ time: now_time }, { $inc: { visited_count: 1,star_count:0 } }, { upsert: true }, function (err, vs) {
        if (!err) {
          res.send({ code: 0, data: passages })
        } else {
          res.send({ code: 1, msg: '出错了' })
        }
      })
    } else {
      res.send({ code: 1, msg: '更新数据失败' })
    }
  })
  /* PassageModel.updateOne({_id:passageID},{visited:visited+1},function(passage){
    console.log('访客数量更新成功',package.visited)
  }) */
});
// 对文章进行评论
router.post('/passageComment', function(req, res){
  // fromUserID: 评论创建者, userName: 创建者用户名, answer: 评论内容,
  // TargetUserID: 评论回复目标ID(当然一级评论没有回复目标就设置为null),
  // TargetUserName: 评论回复目标用户名, time: 评论创建时间,
  // parentID: 一级评论的id（对应一级评论的fromUserID）,用于向其中添加新的评论内容
  // 对文章进行评论，首先用户需要登录 
  let { fromUserID, userName, answer, TargetUserID, TargetUserName, time, parentID, passageID} = req.body
  UserModel.findOne({_id: fromUserID},function(err, user){
    if(user){
      // 找到文章
      PassageModel.findOne({_id: passageID},function(err, passage){
        if(passage){
          // 取出评论
          let comments = passage.comments
          if(!TargetUserID){
            // 一级评论
            comments.push({fromUserID, userName, answer, TargetUserID, 
              TargetUserName, time, parentID, children: []})
          }else{
            //二级评论 
            for(let i = 0; i < comments.length; i++){
              if(comments[i].fromUserID === parentID){
                comments[i].children.push({fromUserID, userName, answer, TargetUserID, 
                  TargetUserName, time, parentID})
              }
            }
          }
          PassageModel.findOneAndUpdate({_id: passageID},{comments},function(err, pas){
            if(!err){
              res.send({code: 0, msg: '评论成功'})
            }else{
              res.send({code: 1, msg: '评论失败'})
            }
          })
        }else{
          res.send({code: 1, msg: '文章不存在'})
        }
      })
    }else{
      res.send({code: 1, msg: '用户不存在'})
    }
  })
})

// *****************后台的接口*****************
// 添加管理员 
router.post('/addmannager', function (req, res, next) {
  const { Mana_Name,Mana_PWD } = req.body
  let man = new ManagerModel({Mana_Name,Mana_PWD,isSuper: false, isRight: false})
  man.save(function(err,m){
    if(!err){
      res.json({code:0,msg:'注册成功，请等待超级管理员审批，审批通过方可登录'})
    } else{
      res.json({code:1,msg:'用户已经存在'})
    }
  })
})
// 登录接口 
router.post('/login', function (req, res, next) {
  // res.send({data:req.body})
  const { Mana_Name,Mana_PWD } = req.body
  ManagerModel.findOne({Mana_Name},function(err,man){
    if(!err){
     // res.send({code:3,data:man.Mana_PWD})
      // 如果没有找到
      if(!man){
        res.json({code:1,msg:'用户不存在'})
        return
      }
      else if(man.Mana_PWD !== Mana_PWD) { 
        res.send({code:1,msg:'密码错误'})
        return
      }
      else if(!man.isRight){
        res.send({code: 1,msg: '该账号未经过超级管理员授权，请耐心等待'})
      }
      else {
        setToken(Mana_Name,Mana_PWD).then(token =>{
          // 将token保存到cookie中并设定有效时间
          res.cookie('token',token,{maxAge:1000*60*60}) 
          res.send({code:0,msg:'登录成功',data:{...(man._doc), Mana_PWD: 0}})
        })
      }
    } else{
      res.json({code:1,msg:'出bug了'}) 
    }
  })
})

// 自动登录接口
router.post('/autoLogin', function (req, res, next) {
  const token = req.cookies.token
  if(!token){
    res.send({code:1,msg:'请先登录'})
    return;
  }
  verToken(token).then(data =>{
    let {username, password} = data
    ManagerModel.findOne({Mana_Name:username},function(err,man){
      if(!err){
        if(man.Mana_PWD!== password) res.json({code:1,msg:'用户伪造令牌'})
        else res.json({code:0,msg:'自动登录成功',data:{...(man._doc), Mana_PWD: 0}})
      } else{
        res.json({code:1,msg:'用户伪造令牌'})
      }
    })
  })
})

// 文章的发布日期排序 （统计某七天发布文章数量 评论数，浏览量，star量）  
router.get('/PassagePublicSort', function (req, res, next) {
  let { cur_day } = req.query
  // 根据当前的日期生成前七天的日期
  let time_list = []
  for (let i = 6; i >= 0; i--) {
    //console.log(cur_day - (i + 1) * 24 * 60 * 60 * 1000)
    time_list.push(timestampToTime(cur_day - (i + 1) * 24 * 60 * 60 * 1000))
  }
  // res.send({code:0,day:time_list})
  let result = {}
  time_list.map(item => {
    result[item] = {}
    result[item].pas = 0
    result[item].visited = 0
    result[item].stars = 0
  })
  // res.send(result)
  // 查询visit中
  VisitedAndStarModel.find({}, function (err, vis) {
    if (!err) {
      vis.map(item => {
        if (timestampToTime(item.time) in result) {
          result[timestampToTime(item.time)].visited = item.visited_count
          result[timestampToTime(item.time)].stars = item.star_count
        }
      })
      // 查询passage
      PassageModel.find({}, filter2, function (err, pas) {
        if (!err) {
          // 对查询出来的时间数据进行排序，并统计个数
          let timepickList = pas.map((item) => {
            return timestampToTime(item.create_time)
          })
          let sortList = timepickList.reduce((pre, cur, index, arr) => {
            if (cur in pre) {
              pre[cur] += 1
            } else {
              pre[cur] = 1
            }
            return pre
          }, {})
          // 将个数添加到最终的result中
          let tempkeys = Object.keys(sortList)
          tempkeys.map(item => {
            if (item in result) {
              result[item].pas = sortList[item]
            }
          })
          res.send({ code: 0, data: result })
        }
        else res.send({ code: 1, msg: '文章数据库崩了' })
      })
    } else {
      res.send({ code: 1, msg: '浏览量数据库崩了' })
    }
  })
})

//添加分类
router.post('/addCategory', function (req, res, next) {
  const { categoryName } = req.body
  let create_time = update_time = new Date()
  const category = new CategoryModel({ create_time, update_time, categoryName })
  category.save(function (err, category) {
    if (category) {
      res.send({ code: 0 })
    } else {
      res.send({ code: 1, msg: '创建分类失败' })
    }
  })
})
// 查询所有分类
router.get('/getCategory', function (req, res, next) {
  CategoryModel.find({}, function (err, categorys) {
    if (!err) res.send({ code: 0, data: categorys })
    else res.send({ code: 1, msg: '获取分类数据失败，请减产网络状态' })
  })
})
//修改分类
router.post('/updateCategory', function (req, res, next) {
  const { _id, newName } = req.body
  CategoryModel.updateOne({ _id }, { $set: { categoryName: newName, update_time: new Date() } }, function (err, status) {
    if (!err) res.send({ code: 0, data: status })
    else res.send({ code: 1, msg: '修改失败，请检查网络' })
  })
})
// 删除分类
router.post('/deleteCategory', function (req, res, next) {
  const { _id } = req.body
  CategoryModel.deleteOne({ _id }, function (err, ca) {
    if (!err) res.send({ code: 0, data: ca })
    else res.send({ code: 1, msg: '修改失败，请检查网络' })
  })
})
// 获取文章的详情 这里用到分页管理
router.post('/passage_detail', function (req, res, next) {
  const { pageNum, pageSize } = req.body
  PassageModel.aggregate([
    {
      $lookup: {
        from: 'categories',
        localField: "categoryID",
        foreignField: "_id",
        as: "cate",
      }
    }

  ], function (err, docs) {
    console.log(err)
    res.send({ code: 0, data: pageFilter(docs, pageNum, pageSize) })
  })
  /* PassageModel.find({},filter2,function(error,passages){
        if(!error){
          // 查询id对应的分类数据表中的分类信息
          let passage_info = pageFilter(passages, pageNum, pageSize)
          let categoryIDList = []
          let temp = passage_info.list.length
          for(let i=0;i<temp;i++){
            if(passage_info.list[i].categoryID){
              categoryIDList.push(passage_info.list[i].categoryID)
            }else{
              categoryIDList.push('')
            }
          }
          //查询这些id对应的值
          
          CategoryModel.find(categoryIDList,function(err,result){
            res.send({code:0,data:result})
          })
          
        }
        else res.send({code:1,msg:'后台崩了'})
    }) */
});
//获取分类名称
router.post('/queryCategoryName', function (req, res, next) {
  const { _id } = req.body
  CategoryModel.findOne({ _id }, function (err, category) {
    if (!err) res.send({ code: 0, data: category.categoryName })
    else res.send({ code: 1, msg: '该分类不存在' })
  })
})
// 删除文章
router.post('/deletePassage', function (req, res, next) {
  let { _id } = req.body
  PassageModel.deleteOne({ _id }, function (err, pas) {
    if (!err) {
      console.log('删除成功')
      res.send({ code: 0 })
    } else {
      console.log('删除失败')
      res.send({ code: 1, msg: '删除失败' })
    }
  })
})

//写文章
router.post('/addPassage', function (req, res, next) {

  const { title, info, context, categoryID, tags, authorID, authorName } = req.body
  /*               //废除passageID:{type:String,require:true},//文章的ID
     =create_time:{type:Number,require:true}, //创建时间
     =visited:{type:Number},//文章的访问量
     =title:{type:String,require:true},//文章标题
     =stars:{type:Number,require:true},//文章的关注数
    = info:{type:String,require:true},//文章的摘要
     =context:{type:String,require:true},//文章的内容
     //功能拓展
     categoryID:{type:String,require:true},//文章所属的分类
     tags:{type:Array,require:true},//文章的标签
     update_time: {type:Number,require:true} ,//文章的更新时间
     */



  const create_time = new Date()
  const update_time = create_time
  const visited = 0
  const stars = 0
  const comments = []
  const isAuthor = false
  const passage = { create_time, visited, title, stars, info, context, categoryID, tags, update_time, comments, authorID, authorName, isAuthor}
  const PassageModelone = new PassageModel(passage)
  //调用save保存
  PassageModelone.save(function (error, user) {
    if (user) {
      res.send({ code: 0 })
    } else {
      res.send({ code: 1, msg: '文章上传失败' })
    }
  })
});
// 文章数据库快捷操作接口，不对外开放, 此接口慎用！！！
router.post('/reUpdatePas',function(req, res){
  let authorID = '60bd79f235dc3f3ec0dcc79a'
  let authorName = '飞飞'
  let isAuthor = true
  let comments = []
  PassageModel.updateMany({},{authorID, authorName, isAuthor, comments}, function(err, doc){
    if(!err){
      res.send({code: 0, msg: '文章数据库大更改成功'})
    }else{
      res.send({code: 1, msg: '文章数据库大更改失败'})
    }
  })
})
// 修改文章
router.post('/UpdatePassage', function (req, res, next) {

  const { _id, title, info, context, categoryID, tags } = req.body
  /*               //废除passageID:{type:String,require:true},//文章的ID
     =create_time:{type:Number,require:true}, //创建时间
     =visited:{type:Number},//文章的访问量
     =title:{type:String,require:true},//文章标题
     =stars:{type:Number,require:true},//文章的关注数
    = info:{type:String,require:true},//文章的摘要
     =context:{type:String,require:true},//文章的内容
     //功能拓展
     categoryID:{type:String,require:true},//文章所属的分类
     tags:{type:Array,require:true},//文章的标签
     update_time: {type:Number,require:true} ,//文章的更新时间
     */
  const update_time = new Date()
  PassageModel.findByIdAndUpdate({ _id }, { title, info, context, categoryID, tags, update_time }, function (err, pas) {
    if (!err) res.send({ code: 0, data: pas })
    else res.send({ code: 1, msg: '文章修改失败' })
  })
});
// 获取文章的全部内容
router.post('/passage_allcontext', function (req, res, next) {

  const { _id } = req.body
  PassageModel.findById({ _id }, function (err, pas) {
    if (!err) res.send({ code: 0, data: pas })
    else res.send({ code: 1, msg: '获取文章失败' })
  })
});

// 分页函数
function pageFilter(arr, pageNum, pageSize) {
  pageNum = pageNum * 1
  pageSize = pageSize * 1
  const total = arr.length
  const pages = Math.ceil(total / pageSize) // 总页数
  const start = pageSize * (pageNum - 1) //计算分页的起始位置
  const end = start + pageSize <= total ? start + pageSize : total //结束位置
  const list = [] // 返回分页列表
  for (var i = start; i < end; i++) {
    list.push(arr[i])
  }

  return {
    pageNum,
    total,
    pages,
    pageSize,
    list
  }
}

// 日期格式化函数
function timestampToTime(timestamp, type = 'YMD') {
  var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  //return Y+M+D+h+m+s;
  if (type === 'YMDHMS') return Y + M + D + h + m + s
  return Y + M + D
}

// 生成token
function setToken(username,password){
	return new Promise((resolve,reject)=>{
		const token = jwt.sign({
			username,
			password
		},signkey);
    // { expiresIn:'1.00h' }
		resolve(token);
	})
}
// 验证token是否还有效

function verToken (token){
	return new Promise((resolve,reject)=>{
    jwt.verify(token,signkey,function(err,data){
      if(!err) resolve(data);			//正确就是null
      else reject(0) // 验证失败
    })
	})
}


//上传图片的路由
require('./fileUpload')(router)
// 上传头像的路由
require('./headUpload')(router)
// 驾考宝典的路由
require('./jiakao')(router)
// 天气接口
require('./weather')(router)
// 用户登录注册
require('./user')(router)
// bug审批
require('./reviewBug')(router)
// 管理员审批
require('./reviewMannager')(router)
// 文章审批
require('./reviewPas')(router)
module.exports = router;
